"""
Copyright (c) 2022 Huawei Technologies Co.,Ltd.

openGauss is licensed under Mulan PSL v2.
You can use this software according to the terms and conditions of the Mulan PSL v2.
You may obtain a copy of Mulan PSL v2 at:

          http://license.coscl.org.cn/MulanPSL2

THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
See the Mulan PSL v2 for more details.
"""
"""
Case Type   : DMS分布式锁
Case Name   : 匿名块获取锁、解锁、锁冲突操作
Create At   : 2023/4/21
Owner       : opentestcase033
Description :
    1.创建测试表
    2.开启事务A，执行只含有DML语句的匿名块，事务B执行后提交
    3.备机开启事务B查看表数据，事务C执行后提交
    4.开启事务C执行含有DDL语句的匿名块，不提交
    5.清理环境
Expect:
    1.成功
    2.执行成功，获取锁
    3.查询为空，事务A提交(解锁)后，事务B执行成功
    4.执行阻塞，事务B提交后执行成功
    5.成功
History     :
"""

import os
import time
import unittest

from testcase.utils.Logger import Logger
from testcase.utils.Common import Common
from testcase.utils.CommonSH import CommonSH
from testcase.utils.Constant import Constant
from testcase.utils.ComThread import ComThread


class DmsOck(unittest.TestCase):

    def setUp(self):
        self.log = Logger()
        self.log.info(f'-----{os.path.basename(__file__)} start-----')
        self.pri_sh = CommonSH('PrimaryDbUser')
        self.std_sh = CommonSH('Standby1DbUser')
        self.constant = Constant()
        self.table = 't_dms_ock_0020'

    def test_dms_ock(self):
        text1 = '-----step1:创建测试表;expect:成功-----'
        self.log.info(text1)
        create_tb = f"drop table if exists {self.table};" \
                    f"create table {self.table}(" \
                    f"sk integer,id char(16),name varchar(20)," \
                    f"sq_ft integer) with (segment = on);"
        create_tb_res = self.pri_sh.execut_db_sql(create_tb)
        self.log.info(create_tb_res)
        self.assertIn(self.constant.CREATE_TABLE_SUCCESS, create_tb_res,
                      f"执行失败:{text1}")

        text2 = '-----step2:开启事务A，执行只含有DML语句的匿名块，' \
                '事务B执行后提交;expect:执行成功，获取锁-----'
        self.log.info(text2)
        sql1 = f'''start transaction;
        declare
        begin
          insert into t_dms_ock_0020 values (008,'sk1','tt',3332);
        end;
        select pg_sleep(3);
        end;'''
        session1 = ComThread(self.pri_sh.execut_db_sql, args=(sql1,))
        session1.setDaemon(True)
        session1.start()
        time.sleep(1)

        text3 = '-----step3:备机开启事务B查看表数据，事务C执行后提交;' \
                'expect:查询为空，事务A提交(解锁)后，事务B执行成功-----'
        self.log.info(text3)
        sql2 = f'''begin;
        select * from {self.table};
        select pg_sleep(3);
        end;'''
        session2 = ComThread(self.pri_sh.execut_db_sql, args=(sql2,))
        session2.setDaemon(True)
        session2.start()
        time.sleep(2)

        text4 = '-----step4:开启事务C执行含有DDL语句的匿名块，不提交;' \
                'expect:执行阻塞，事务B提交后执行成功-----'
        self.log.info(text4)
        sql2 = f'''begin;
        declare
        begin
          drop table if exists t_dms_ock_0020;
        end; '''
        session3 = ComThread(self.pri_sh.execut_db_sql, args=(sql2,))
        session3.setDaemon(True)
        session3.start()
        session1.join(10)
        session2.join(10)
        session3.join(10)
        result1 = session1.get_result()
        self.log.info(f'session1_results: {result1}')
        result2 = session2.get_result()
        self.log.info(f'session2_results: {result2}')
        result3 = session3.get_result()
        self.log.info(f'session3_results: {result3}')
        self.assertTrue(self.constant.START_TRANSACTION_SUCCESS_MSG in result1
                        and self.constant.COMMIT_SUCCESS_MSG in result1,
                        f"执行失败:{text2}")
        self.assertEqual(result2.splitlines()[3].strip(), '(0 rows)',
                         f"执行失败:{text3}")
        self.assertIn(self.constant.COMMIT_SUCCESS_MSG, result2,
                      f"执行失败:{text3}")
        self.assertIn(self.constant.ANONYMOUS_BLOCK_EXECUTE_SUCCESS_MSG,
                      result3, f"执行失败{text4}")

    def tearDown(self):
        text4 = '-----step5:清理环境 expect:成功-----'
        self.log.info(text4)
        drop_res = self.pri_sh.execut_db_sql(
            f"drop table if exists {self.table} cascade;")
        self.log.info(drop_res)
        self.assertIn(self.constant.DROP_TABLE_SUCCESS,
                      drop_res, f"删表失败:{text4}")
        self.log.info(f'-----{os.path.basename(__file__)} end-----')
